import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_quill/flutter_quill.dart';
import 'package:toastification/toastification.dart';

import 'entry_add_cubit.dart';

class EntryAddPage extends StatefulWidget {
  const EntryAddPage({super.key});

  @override
  State<EntryAddPage> createState() => _EntryAddPageState();
}

class _EntryAddPageState extends State<EntryAddPage> {
  final QuillController _controller = QuillController.basic();

  final TextEditingController _nameController = TextEditingController();
  final TextEditingController _tagController = TextEditingController();
  late BuildContext buildContext;

  @override
  void initState() {
    super.initState();
    _nameController.addListener(_onNameChanged);
    _controller.addListener(_onRichTextChanged);
  }

  void _onNameChanged() {
    buildContext.read<EntryAddCubit>().updateName(_nameController.text);
  }

  void _onRichTextChanged() {
    debugPrint('_onRichTextChanged');
  }

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => EntryAddCubit(),
      child: BlocBuilder<EntryAddCubit, EntryAddState>(
        builder: (BuildContext context, EntryAddState state) {
          buildContext = context;
          return SafeArea(
            child: Scaffold(
              backgroundColor: Colors.white,
              appBar: AppBar(title: Text("创建条目")),
              body: Container(
                padding: EdgeInsets.fromLTRB(16, 0, 16, 0),
                child: Column(
                  children: [
                    // 标题
                    TextField(controller: _nameController, decoration: InputDecoration(labelText: '名称', hintText: '至少一个字符')),
                    // tag 地理信息 品牌等
                    TextField(
                      controller: _tagController,
                      decoration: InputDecoration(
                        labelText: '标签',
                        hintText: '至少一个字符，点击右边加号添加',
                        suffixIcon: IconButton(
                          icon: const Icon(Icons.add),
                          onPressed: () {
                            context.read<EntryAddCubit>().addTags(_tagController.text);
                            _tagController.clear();
                          },
                        ),
                      ),
                    ),
                    const SizedBox(height: 16),
                    SizedBox(
                      width: double.infinity,
                      child: Wrap(
                        spacing: 8.0,
                        runSpacing: 8,
                        children:
                            state.tags
                                .map(
                                  (tag) => Chip(
                                    label: Text(tag),
                                    onDeleted: () {
                                      state.tags.remove(tag);
                                    },
                                  ),
                                )
                                .toList(),
                      ),
                    ),
                    const SizedBox(height: 16),
                    QuillSimpleToolbar(controller: _controller, config: const QuillSimpleToolbarConfig(showFontFamily: false)),
                    Expanded(child: QuillEditor.basic(controller: _controller, config: const QuillEditorConfig())),
                    Container(
                      width: double.infinity,
                      padding: EdgeInsets.fromLTRB(0, 20, 0, 20),
                      child: ElevatedButton(
                        onPressed: () {
                          buildContext.read<EntryAddCubit>().updateRichText(_controller.document.toPlainText());
                          //错误提示
                          var text = "";
                          if (state.name.isEmpty) {
                            text = "名称不能为空";
                          } else if (state.tags.isEmpty) {
                            text = "至少添加一个标签";
                          }
                          toastification.show(
                            type: ToastificationType.error,
                            context: context, // optional if you use ToastificationWrapper
                            title: Text(text),
                            autoCloseDuration: const Duration(seconds: 5),
                          );
                          context.read<EntryAddCubit>().submit(context);
                        },
                        child: Text('提交'),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          );
        },
      ),
    );
  }

  @override
  void dispose() {
    _nameController.dispose();
    _controller.dispose();
    super.dispose();
  }
}
